import 'dart:io';
import 'dart:isolate';

import 'package:excel/excel.dart';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';

class DelBlankRowsPage extends StatefulWidget {
  const DelBlankRowsPage({super.key});

  @override
  State<DelBlankRowsPage> createState() => _DelBlankRowsPageState();
}

class _DelBlankRowsPageState extends State<DelBlankRowsPage> {
  // 选择的数据
  List<File> childFiles = [];
  StringBuffer progressRes = StringBuffer();

  showSnackBar(Text msg) {
    ScaffoldMessenger.of(context)..hideCurrentSnackBar()..showSnackBar(SnackBar(content: msg));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(title: Text("Delete Blank Rows")),
        body: Container(
          child: Row(
            children: [
              Expanded(
                  child: Column(
                children: [
                  ElevatedButton(
                    onPressed: () async {
                      var filePickerResult = await FilePicker.platform.pickFiles(allowedExtensions: ['xlsx'], type: FileType.custom, allowMultiple: true);
                      if (filePickerResult != null) {
                        final Set<String> addedFilePaths = childFiles.map((file) => file.path).toSet(); // 将已有文件路径存入 Set 中
                        for (var value in filePickerResult.files) {
                          var filePath = value.path.toString();
                          // 判断文件路径是否已经添加过
                          if (!addedFilePaths.contains(filePath)) {
                            childFiles.add(File(filePath)); // 新增文件
                            addedFilePaths.add(filePath); // 更新已添加文件路径的 Set
                          }
                        }
                        print(childFiles);
                        setState(() {});
                      }
                    },
                    child: Text("选择文件 ${childFiles.length}"),
                  ),
                  Expanded(
                      child: ListView.separated(
                    padding: EdgeInsets.all(10),
                    itemBuilder: (BuildContext context, int index) {
                      return Text(childFiles[index].path);
                    },
                    itemCount: childFiles.length,
                    separatorBuilder: (BuildContext context, int index) {
                      return Divider();
                    },
                  ))
                ],
              )),
              Expanded(
                  child: Column(
                children: [
                  ElevatedButton(
                    onPressed: () async {
                      progressRes.clear();
                      setState(() {});
                      ReceivePort receivePort = ReceivePort();
                      final args = {"sendPort": receivePort.sendPort, "data": childFiles, "sheetName": "CMS、Sheet2、Attend Modifier Result"};
                      await Isolate.spawn(deleteBlankRowsData, args);
                      receivePort.listen((data) {
                        print(data);
                        progressRes.write(data["msg"]);
                        setState(() {});
                      });
                    },
                    child: Text(key: UniqueKey(), "Remove Blank Rows"),
                  ),
                  Expanded(
                    child: SingleChildScrollView(
                      child: Text("进度: ${progressRes.toString()}"),
                    ),
                  ),
                ],
              )),
            ],
          ),
        ));
  }
}

deleteBlankRowsData(Map<String, dynamic> extractMap) {
  SendPort sendPort = extractMap["sendPort"];
  List<File> childFiles = extractMap["data"];
  List<String> sheetNames = extractMap["sheetName"].split("、");
  List<String> results = [];

  for (var file in childFiles) {
    StringBuffer progressRes = StringBuffer();
    // 查看有多少行数据
    Excel excel = Excel.decodeBytes(file.readAsBytesSync());
    var sheetName = "";
    for (var sheetNameTemp in sheetNames) {
      var table = excel.tables["${sheetNameTemp}"];
      if (table != null) {
        sheetName = sheetNameTemp;
        break;
      }
    }
    progressRes.write("正在处理文件: ${file.path}");
    var sheetData = excel.tables["$sheetName"];
    // 查看有多少行数据
    int rowNum = sheetData!.rows.length;
    print("行数: $rowNum");
    List<List<Data?>> rows = sheetData.rows;
    // 从最后一行开始遍历，如果遇到空白行则删除
    for (int i = rowNum - 1; i >= 0; i--) {
      var rowData = rows[i];
      var index0Data = rowData[0];
      if (index0Data == null || index0Data.value.toString().trim() == "") {
        sheetData.removeRow(i);
        //已删除的行数
        progressRes.write("\n已删除的行数: $i");
      }
    }
    // 还剩下
    progressRes.write("\n剩余行数: ${rows.length}");
    // 写入之后进行保存到他本身
    final bytes = excel.encode();
    dynamic result = {};
    try {
      progressRes.write("\n正在写入到文件中，请稍后...");
      file.writeAsBytesSync(bytes!);
      progressRes.write("\n写入成功");
      result = {"code": 0, "msg": "${progressRes.toString()}"};
      sendPort.send(result);
    } catch (e) {
      print(e.toString());
      if (e is PathAccessException) {
        result = {"code": 1, "msg": "文件被占用"};
        results.add(result);
      }
    }
  }
}
